package com.yifushidai.service;

import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.utils.CustomPackUtils;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import com.yifushidai.utils.ShisuMinaPushUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class MacUnbindService {

    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;

    public R queryByMac(String mac) throws Exception {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);
        return R.ok().put(one);
    }


    public R lockMacUnbind(String mac, HttpServletRequest request) throws Exception {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        Object res = ShisuMinaPushUtils.push(mac, "lockMacUnbind:NA");
        if ("OK".equals(res)) {
            one.setLockMac(null);
            return R.ok().put(apiUniqueMacMapper.updateByPrimaryKey(one));
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

    public R cardMacUnbind(String mac, HttpServletRequest request) throws Exception {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        Object res = ShisuMinaPushUtils.push(mac, "cardMacUnbind:NA");
        if ("OK".equals(res)) {
            one.setCardMac(null);
            return R.ok().put(apiUniqueMacMapper.updateByPrimaryKey(one));
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

    public R powerMacUnbind(String mac, HttpServletRequest request) throws Exception {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        Object res = ShisuMinaPushUtils.push(one.getPowerMac(), "powerMacUnbind:NA");
        if ("OK".equals(res)) {
            one.setPowerMac(null);
            one.setPowerStatus(CustomPackUtils.OFF_LINE);
            one.setUpdateTime(new Date());
            return R.ok().put(apiUniqueMacMapper.updateByPrimaryKey(one));
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }
}
